package cn.springcloud.fix.demo.node;

import java.util.Arrays;
import java.util.LinkedList;

public class TreeNodeTest {

    public static void main(String[] args) {
        LinkedList<Integer> inputList = new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null, null, 8, null, 4));
        TreeNode treeNode = createBinaryTree(inputList);
        System.out.println(" 前序遍历:");
        preOrderTraveral(treeNode);
        System.out.println(" 中序遍历:");
        inOrderTraveral(treeNode);
        System.out.println(" 后序遍历:");
        postOrderTraveral(treeNode);
    }

    private static TreeNode createBinaryTree(LinkedList<Integer> inputList) {
        if (inputList == null || inputList.isEmpty()) {
            return null;
        }
        TreeNode node = null;
        Integer data = inputList.removeFirst();
        if (data != null) {
            node = new TreeNode(data);
            node.setLeftChild(createBinaryTree(inputList));
            node.setRightChild(createBinaryTree(inputList));
        }
        return node;
    }

    /**
     * 前序遍历
     */
    private static void preOrderTraveral(TreeNode node) {
        if (node == null) return;

        System.out.println(node.getData());
        preOrderTraveral(node.getLeftChild());
        preOrderTraveral(node.getRightChild());
    }

    /**
     * 中序遍历
     */
    private static void inOrderTraveral(TreeNode node) {
        if (node == null) return;

        inOrderTraveral(node.getLeftChild());
        System.out.println(node.getData());
        inOrderTraveral(node.getRightChild());
    }

    /**
     * 后续遍历
     */
    private static void postOrderTraveral(TreeNode node) {
        if (node == null) return;

        postOrderTraveral(node.getLeftChild());
        postOrderTraveral(node.getRightChild());
        System.out.println(node.getData());
    }
}
